import pyglet
from message import *
from pyglet.window import key,mouse
from pyglet.gl import *


window = pyglet.window.Window()

@window.event
def on_draw():
    window.clear()
    send_message(Msg(MSG_DRAW))

@window.event
def on_key_press(symbol, modifiers):
    send_message(Msg(MSG_KEY, None, symbol))

@window.event
def on_mouse_press(x, y, button, modifiers):
    if button == mouse.LEFT:
        send_message(Msg(MSG_LBUTTONDOWN, None, (x,y)))
    elif button == mouse.RIGHT:
        send_message(Msg(MSG_RBUTTONDOWN, None, (x,y)))
        
@window.event
def on_mouse_release(x, y, button, modifiers):
    if button == mouse.LEFT:
        send_message(Msg(MSG_LBUTTONUP, None, (x,y)))
    elif button == mouse.RIGHT:
        send_message(Msg(MSG_RBUTTONUP, None, (x,y)))

@window.event
def on_mouse_motion(x, y, dx, dy):
    send_message(Msg(MSG_MOUSEMOVE, None, (x, y, dx, dy)))

##################################################################
    
def timer_callback(dt):
    send_message(Msg(MSG_TIMER))
    
def draw_line(a, b):
    pyglet.graphics.draw(2, GL_LINES,
                         ('v2i', (a[0], a[1], b[0], b[1])))

def fill_rect(rect, color):
    glColor3f (color[0], color[1], color[2]);
    x,y,w,h = rect
    glBegin(GL_POLYGON);
    glVertex3f (x, y, 0.0);
    glVertex3f (x+w, y, 0.0);
    glVertex3f (x+w, y+h, 0.0);
    glVertex3f (x, y+h, 0.0);
    glEnd();
    glColor3f (0.1, 0.1, 0.1);

def draw_text(text, x, y, size = 9, color = (0,0,0,255)):
    pyglet.text.Label(text,
                      font_name = 'Times New Roman',
                      font_size = size,
                      color = color,
                      x = x, y = y).draw()
    
################################
        
__observers = {}

def set_msg_observer(msg_type, observer):
    __observers[msg_type] = observer

def send_message(msg):
    obs = __observers[msg.type]
    obs.sys_message(msg)
    
def run():
#    send_message(Msg(MSG_KEY, value='a'))
#    send_message(Msg(MSG_LBUTTONDOWN, 'LBUTTONDOWN', (50,50)))
#    send_message(Msg(MSG_LBUTTONUP, 'LBUTTONUP', (50,50)))
#    send_message(Msg(MSG_LBUTTONUP, 'LBUTTONUP', (0,150)))
#    send_message(Msg(MSG_TIMER))
#    pyglet.clock.schedule_interval(timer_callback, .5)    
    pyglet.app.run()
